import {
  createRouter,
  createWebHistory
} from "vue-router";
import {
  decode
} from "js-base64";
import {
  routes
} from "./router";
import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({
  showSpinner: false,
});

// 创建一个路由对象
const router = createRouter({
  history: createWebHistory(),
  routes: [...routes],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else {
      return {
        top: 0,
      };
    }
  },
});

const goHome = (userInfo, next) => {
  if (!userInfo) {
    next('/')
  } else {
    let userJObj = JSON.parse(userInfo);
    const type = userJObj['type'].toLowerCase();
    if (type === 'student') {
      next("/student/process")
    }
    if (type === 'teacher') {
      next("/teacher/approve")
    }
    if (type === 'account') {
      next("/account/notify")
    }
  }
}

// 设置路由权限
router.beforeEach((to, from, next) => {
  NProgress.start();

  document.title =
    to.meta && to.meta.title ?
    to.meta.title + " - " +
    import.meta.env.VITE_APP_TITLE :
    "管理系统";

  const jwtToken = sessionStorage.getItem("jwt") || "";
  const userInfo = sessionStorage.getItem("user") || "";
  const whiteList = ["/login"]; // 路由白名单

  // 进入路由白名单
  // if (to.path === "/login") {
  if (whiteList.includes(to.path)) {
    !!jwtToken ? next('/') : next();
  } // 在白名单就可以进入
  else {
    if (from.name === "Login" && !jwtToken) {
      next(false);
      return false;
    }
    if (!!jwtToken) {
      if (to.meta.hasOwnProperty("roles")) {
        let roles = to.meta.roles || [];
        // let {
        //     role
        // } = jwtToken && JSON.parse(decode(jwtToken));
        let userJObj = JSON.parse(userInfo);
        let type = userJObj["type"];
        roles.includes(type) ? next() : next("/error");
        return false;
      }
      next();
    } // 令牌还在
    else {
      next("/login");
    } // 登录令牌不存在
  }
});

router.afterEach(() => {
  NProgress.done();
});

export default router;